<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="90px">
      <!-- 新增所属风场下拉框 -->
      <el-form-item label="所属风场" prop="ssfc">
        <el-select
          v-model="form.ssfc"
          placeholder="请选择所属风场"
          clearable
          filterable
          style="width: 100%"
          @change="handleSsfcChange"
        >
          <el-option
            v-for="item in ssfcOptions"
            :key="item.windFarmId"
            :label="item.name"
            :value="item.windFarmId"
          />
        </el-select>
      </el-form-item>
      <!-- 设备信息下拉选择 -->
      <el-form-item label="选择设备" prop="deviceInfo" v-show="ssfcDj">
        <el-select style="width: 100%;" v-model="form.deviceInfo" placeholder="请选择设备" filterable clearable
          @change="handleDeviceChange" :value-key="'id'">
          <el-option v-for="item in deviceOptions" :key="item.id" :label="`${item.turbineCode}`" :value="item">
            <span style="float: left">{{ item.turbineCode }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">
              {{ item.turbineModel }} | {{ item.id }}
            </span>
          </el-option>
        </el-select>
      </el-form-item>

      <!-- 其他表单字段保持不变 -->
      <el-form-item label="故障类型" prop="sbsx">
        <el-select
          v-model="form.sbsx"
          placeholder="请选择故障类型"
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="item in sbsxOptions"
            :key="item.value"
            :label="item.label"
            :value="item.label"
          />
        </el-select>
      </el-form-item>


      <el-form-item label="上报人" prop="sbr">
        <el-input v-model="form.sbr" placeholder="请输入上报人" />
      </el-form-item>
<!--      <el-form-item label="上报单位" prop="sbdw">-->
<!--        <el-input v-model="form.sbdw" placeholder="请输入上报单位" />-->
<!--      </el-form-item>-->
      <el-form-item label="上报时间" prop="sbsj">
        <el-date-picker v-model="form.sbsj" type="datetime" placeholder="选择时间" value-format="yyyy-MM-dd HH:mm:ss"
          style="width: 100%;" />
      </el-form-item>
      <el-form-item label="故障描述" prop="gzms">
        <el-input v-model="form.gzms" type="textarea" placeholder="请输入内容" />
      </el-form-item>
      <el-form-item label="图片和视频" prop="picVideo">
        <imageV-upload v-model="form.picVideo" :image-limit="5" :video-limit="5" :file-size="2" :video-size="100" />
      </el-form-item>
      <input type="hidden" name="type" value="1">
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: center;">
      <el-button type="primary" @click="submitForm">保 存</el-button>
    </div>
  </div>
</template>

<script>
import { addMaintenance } from "@/api/system/maintenance"
import { listTurbineGZSB, ssfcList } from "@/api/system/turbine"
import { login, logout, getInfo } from '@/api/login'

export default {
  name: "Maintenance",
  data() {
    return {
      deviceOptions: [],
      ssfcOptions: [], // 新增：所属风场选项
      ssfcDj:false,
      form: {
        deviceInfo: null, // 存储选中的设备对象
        zbmc: '',       // 设备名称
        sbbh: '',       // 设备编号
        sbid: '',       // 设备ID
        sbsx: '',
        ssfc: '',       // 新增：所属风场ID
        ssfcmc: ''    // 新增：所属风场名称（可选）
      },
      // 下拉选项
      sbsxOptions: [
        { value: '1', label: '离线' },
        { value: '2', label: '检修' },
        { value: '3', label: '故障' },
      ],
      rules: {
        ssfc: [
          { required: true, message: '请选择所属风场', trigger: 'change' }
        ],
        deviceInfo: [
          { required: true, message: '请选择设备信息', trigger: 'change' }
        ],
        sbsx: [
          { required: true, message: '请选择设备属性', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.fetchSsfcList() // 新增：获取所属风场列表
  },
  methods: {
    // 新增：获取所属风场列表
    async fetchSsfcList() {
      try {
        const res = await ssfcList()
        if (res.code === 200) {
          this.ssfcOptions = res.rows || res.data || []

          // 默认选中第一个选项（如果有选项）
          if (this.ssfcOptions.length > 0) {
            this.form.ssfc = this.ssfcOptions[0].windFarmId
            this.form.ssfcmc = this.ssfcOptions[0].name

            // 自动触发风场变化逻辑
            this.handleSsfcChange(this.form.ssfc)
          }
        }
      } catch (error) {
        console.error('获取所属风场列表失败:', error)
        this.$message.error('获取所属风场列表失败')
      }
    },

    // 新增：处理风场选择变化
    handleSsfcChange(value) {
      this.ssfcDj=true
      this.fetchTurbineList()
      const selectedSsfc = this.ssfcOptions.find(item => item.windFarmId === value)
      if (selectedSsfc) {

        this.form.ssfcmc = selectedSsfc.name // 可选：保存风场名称
      } else {
        this.form.ssfcmc = ''
      }
    },

    async fetchTurbineList() {
      getInfo().then(res => {
          const user = res.user
          this.form.sbr = user.nickName
        }).catch(error => {
        })
      try {

        const res = await listTurbineGZSB({location:this.form.ssfc})
        if (res.code === 200) {
          this.deviceOptions = res.rows.map(item => ({
            ...item,
            uniqueKey: `${item.id}_${Date.now()}`
          }))
        }
      } catch (error) {
        console.error('获取设备列表失败:', error)
        this.$message.error('获取设备列表失败')
      }
    },

    handleDeviceChange(selected) {
      if (selected) {
        this.form.zbmc = selected.turbineCode
        this.form.sbbh = selected.turbineModel
        this.form.sbid = selected.id
        const selectedItem = this.deviceOptions.find(item => item.id === selected.id)
        this.form.deviceInfo = selectedItem
      } else {
        this.clearDeviceSelection()
      }
    },

    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const currentSelection = this.form.deviceInfo
          if (currentSelection) {
            this.form.zbmc = currentSelection.turbineCode
            this.form.sbbh = currentSelection.turbineModel
            this.form.sbid = currentSelection.id
          }

          // 准备提交数据
          const submitData = {
            ...this.form,
            type: 0,
            // 确保提交风场ID
            ssfc: this.form.ssfc,
            // 如果需要也可以提交风场名称
            ssfcmc: this.form.ssfcmc
          }

          // 移除不需要提交的字段
          delete submitData.deviceInfo

          addMaintenance(submitData).then(response => {
            this.$modal.msgSuccess("保存成功")
            this.resetForm()
          }).catch(error => {
            console.error('保存失败:', error)
          })
        }
      })
    },

    clearDeviceSelection() {
      this.form.deviceInfo = null
      this.form.zbmc = ''
      this.form.sbbh = ''
      this.form.sbid = ''
    },

    resetForm() {
      this.form = {
        deviceInfo: null,
        zbmc: '',
        sbbh: '',
        sbid: '',
        sbsx: '',
        sbr: '',
        sbdw: '',
        sbsj: '',
        picVideo: '',
        gzms: '',
        ssfc: '',    // 重置风场ID
        ssfcmc: '' // 重置风场名称
      }
      this.$refs.form.resetFields()
    }
  }
}
</script>

<style>
/* 优化下拉选项显示 */
.el-select-dropdown__item {
  display: flex;
  justify-content: space-between;
  padding: 0 20px;
}
</style>
